package store.core;

import store.dao.AccountDao;
import store.dao.CartDao;
import store.dao.CategoryDao;
import store.dao.GoodsDao;
import store.model.Account;
import store.model.Cart;
import store.model.Category;
import store.model.Goods;

import java.sql.SQLException;
import java.util.List;
import java.util.Scanner;

/**
 * 开发喵store
 *
 * @version 1.0
 */
public class Store {

    private static final GoodsDao goodsDao;
    private static final AccountDao accountDao;
    private static final CategoryDao categoryDao;
    private static final CartDao cartDao;

    static {
        goodsDao = new GoodsDao();
        accountDao = new AccountDao();
        categoryDao = new CategoryDao();
        cartDao = new CartDao();
    }

    /**
     * Scanner 对象
     * final 修饰的变量叫做常量,命名时每个单词都大写,单词间使用下划线(_)连接
     */
    private static final Scanner INPUT = new Scanner(System.in);

    public void open() {
        // 打印欢迎语
        welcome();
        // 首页功能列表
        indexMenuList();
    }

    /**
     * 打印欢迎语
     */
    private void welcome() {
        println("*******************************************");
        println("*                                         *");
        println("*          欢迎光临 开发喵Store             *");
        println("*                                         *");
        println("*******************************************");
        println("  (请根据提示输入相应的编号使用本系统) ");
    }

    /**
     * 首页功能列表
     */
    private void indexMenuList() {
        println("1. 会员登录");
        println("2. 注册");
        println("3. 管理员登录");
        println("0. 退出");
        print("请选择：");
        int in = INPUT.nextInt();
        router(in);
    }

    /**
     * 管理员 菜单
     * 20x  20x
     * 200 + in
     */
    public void adminMenuList() {
        println("1. 会员信息");
        println("2. 商品入库");
        println("3. 新增商品分类");
        println("4. 商品列表");
        println("0. 退出");
        print("请选择：");
        int in = INPUT.nextInt();
        if (in != 0) {
            in += 200;
        }
        router(in);
    }


    /**
     * 功能跳转
     */
    private void router(int in) {
        switch (in) {
            case 1 -> login();
            case 2 -> register();
            case 3 -> adminLogin();
            case 201 -> showVipList();
            case 202 -> addGoods();
            case 203 -> addCategory();
            case 204 -> {
                showGoodsList();
                adminMenuList();
            }
            case 0 -> exit();
            default -> {
                print("输入错误，请重新输入:");
                router(INPUT.nextInt());
            }
        }
    }

    /**
     * 显示所有商品列表
     */
    private void showGoodsList() {
        println("商品列表如下：");
        try {
            List<Goods> list = goodsDao.selectAll();
            for (Goods goods : list) {
                if (goods.getCount() > 0) {
                    println(goods.toString());
                }
            }
        } catch (SQLException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 显示所有商品分类信息
     */
    public void showCategory() {
        try {
            List<Category> categories = categoryDao.selectAll();
            println("现有商品分类如下：");
            if (categories.size() > 0) {
                categories.forEach(category -> {
                    println(category.toString());
                });
            } else {
                println("(暂无商品分类)");
            }
        } catch (SQLException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 新增商品分类
     */
    private void addCategory() {
        showCategory();
        print("请输入分类名称:");
        String name = INPUT.next();

        Category category = new Category(name);
        int insert = 0;
        try {
            insert = categoryDao.insert(category);
        } catch (SQLException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        if (insert > 0) {
            println("插入分类成功");
        } else {
            println("插入分类失败");
        }
        adminMenuList();
    }

    /**
     * 商品入库
     */
    private void addGoods() {
        print("请输入商品编号：");
        int no = INPUT.nextInt();
        try {
            // 有没有库存
            Goods goods = goodsDao.selectOne(no);
            if (goods == null) { // 没有库存，入库
                goods = new Goods();
                goods.setGoodNo(no);
                print("请输入商品名称：");
                String goodsName = INPUT.next();
                goods.setGoodsName(goodsName);
                print("请输入商品进价：");
                double cost = INPUT.nextDouble();
                goods.setCost(cost);
                print("请输入商品售价：");
                double price = INPUT.nextDouble();
                goods.setPrice(price);
                showCategory();
                print("请选择商品分类：");
                int category = INPUT.nextInt();
                goods.setCategory_no(category);
                int insert = goodsDao.insert(goods);
                if (insert > 0) {
                    println("添加" + goods.getGoodsName() + "成功");
                } else {
                    println("添加失败");
                }
            } else {
                print("请输入商品数量：");
                int count = INPUT.nextInt();
                goods.setCount(goods.getCount() + count);
                int i = goodsDao.updateCount(goods);
                if (i > 0) {
                    println("添加商品成功!");
                } else {
                    println("添加商品失败");
                }
            }
        } catch (SQLException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        adminMenuList();
    }

    /**
     * 管理员登录
     */
    private void adminLogin() {
        print("请输入电话号：");
        String phone = INPUT.next();
        print("请输入密码：");
        String password = INPUT.next();
        Account login = null;
        try {
            login = accountDao.login(phone, password);
        } catch (SQLException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        if (login != null && !login.isType()) { // 存在并且是管理员
            System.out.println("登录成功，" + login.getName() + "，欢迎您！");
            adminMenuList();
        } else {
            System.out.println("登录失败");
            indexMenuList();
        }
    }

    /**
     * 显示所有会员信息
     */
    private void showVipList() {
        try {
            List<Account> accounts = accountDao.selectAll();
            println("现在共有 " + accounts.size() + " 名会员. 信息如下：");
            println(accounts.toString());
            adminMenuList();
        } catch (SQLException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 退出系统
     */
    private void exit() {
        println("欢迎下次光临！");
        System.exit(0);
    }

    /**
     * 注册
     */
    private void register() {
        println("注册：根据提示输入会员信息.");
        print("请输入手机号：");
        String phone = INPUT.next();
        try {
            Account account = accountDao.checkRegister(phone);
            if (account == null) {
                String pwd = null;
                do {
                    print("请输入密码：");
                    pwd = INPUT.next();
                    print("请再次输入密码：");
                    String pwd2 = INPUT.next();
                    if (!pwd.equals(pwd2)) {
                        println("两次密码不一致，请重新输入！");
                    } else {
                        break;
                    }
                } while (true);
                print("请输入会员姓名：");
                String name = INPUT.next();
                Account account1 = new Account();
                account1.setPhone(phone);
                account1.setPassword(pwd);
                account1.setName(name);
                accountDao.insert(account1);
                println(name + ", 恭喜您称为本店的会员！");
                // 回到上一级
                indexMenuList();
            } else {
                System.out.println("电话已经被注册");
                indexMenuList();
            }
        } catch (SQLException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 登录
     */
    private void login() {
        print("请输入电话号：");
        String phone = INPUT.next();
        print("请输入密码：");
        String password = INPUT.next();
        try {
            Account account = accountDao.login(phone, password);
            if (account != null) {
                System.out.println("登录成功，欢迎" + account.getName() + "登录！");
                shopping(account);
            } else {
                System.out.println("登录失败，电话或密码错误");
                indexMenuList();
            }
        } catch (SQLException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 添加购物车操作
     *
     * @param account 当前登录的账户
     */
    private void shopping(Account account) {
        showGoodsList();
        print("请选择您要购买的商品：");
        // TODO(判断输入有效性)
        int no = INPUT.nextInt();
        // 查询商品是否存在
        try {
            Goods goods = goodsDao.selectOne(no);
            if (goods != null) {
                print("请输入购买 【" + goods.getGoodsName() + "】 的数量：");
                int count = INPUT.nextInt();
                while (goods.getCount() < count) {
                    // 库存不够
                    println("对不起，库存不足。请重新输入：");
                    count = INPUT.nextInt();
                }
                Cart cart = new Cart();
                cart.setAccountId(account.getId());
                cart.setGoodsNO(goods.getGoodNo());
                cart.setNum(count);
                // 添加购物车信息到数据库
                int insert = cartDao.insert(cart);
                if (insert > 0) {
                    println("添加到购物车成功");
                    print("是否继续购物？ 1. 继续购物  2. 结账");
                    int t = INPUT.nextInt();
                    while (t != 1 && t != 2) {
                        print("请输入正确的代码：");
                        t = INPUT.nextInt();
                    }
                    if (t == 1) {
                        shopping(account);
                    } else {
                        pay(account);
                    }
                } else {
                    println("添加购物车失败");
                    shopping(account);
                }
            } else {
                println("请输入已经存在的商品");
                shopping(account);
            }

        } catch (SQLException | ClassNotFoundException e) {
            throw new RuntimeException("购买商品时出错", e);
        }
    }

    private void pay(Account account) {
        println("您本次的购物清单是：");
        try {
            List<Cart> carts = cartDao.selectByAccountId(account.getId());
            println("序号\t商品名称\t单价\t数量\t小计");
            double sum = 0;
            for (int i = 0; i < carts.size(); i++) {
                Cart cart = carts.get(i);
                Goods goods = goodsDao.selectOne(cart.getGoodsNO());
                double eachSum = goods.getPrice() * cart.getNum();
                sum += eachSum;
                println((i + 1) + "\t" + goods.getGoodsName() + "\t" + goods.getPrice() + "\t" + cart.getNum() + "\t" + eachSum);
            }
            println("总计： " + sum + "元");
            println("尊贵的" + account.getName() + "会员，您好，本次购物应收款：" + sum);
            double money = 0.0;
            do {
                print("收款：");
                money = INPUT.nextDouble();
                if (money < sum) {
                    println("付款金额不足，请重新支付.");
                } else {
                    break;
                }
            } while (true);
            println("找零：" + (money - sum));
            // 修改商品库存
            carts.forEach(cart -> {
                try {
                    Goods goods = goodsDao.selectOne(cart.getGoodsNO());
                    if (goods != null) {
                        goods.setCount(goods.getCount() - cart.getNum());
                        int i = goodsDao.updateCount(goods);
                        if (i > 0) {
                            println("修改" + goods.getGoodsName() + "库存成功");
                        } else {
                            println("修改" + goods.getGoodsName() + "库存失败");
                        }

                    }
                } catch (SQLException | ClassNotFoundException e) {
                    throw new RuntimeException(e);
                }
            });
            account.setPoint(account.getPoint() + (int) Math.floor(sum));
            // 修改用户积分
            accountDao.updatePoint(account);
            adminMenuList();
            // TODO 能否升级会员
        } catch (SQLException |
                 ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    public void logout() {
        println("欢迎下次光临！");
        indexMenuList();
    }

    /**
     * 控制台打印封装
     *
     * @param str 打印内容
     */
    public static void println(String str) {
        System.out.println(str);
    }

    public static void print(String str) {
        System.out.print(str);
    }
}
